
import { request } from '../../request/index'

Page({
    data: {
        tabs: [
            {
                id: 0,
                value: '综合',
                isActive: true
            },
            {
                id: 1,
                value: '销量',
                isActive: false
            },
            {
                id: 2,
                value: '价格',
                isActive: false
            },
        ],
        arr: [
            {
                id: '1',
                name: '222',
            },
            {
                id: '3',
                name: '332',
            },
            {
                id: '5',
                name: '33',
            },
        ],
        goodsList: [],
    },
    innerParams: {
        /// 接口参数
        query: "",
        cid: "",
        pagenum: 1,
        pagesize: 10,
    },
    totalPages: 1,
    onLoad: function (options) {
        this.innerParams.cid = options.cid || "";
        this.innerParams.query = options.query || ""
        this.getGoodsList()
    },
    async getGoodsList() {
        const res = await request({
            url: '/goods/search',
            data: this.innerParams
        })
        console.log(res)
        //获取总条数;
        const total = res.total;
        this.totalPages = Math.ceil(total / this.innerParams);

        this.setData({
            goodsList: [...this.data.goodsList, ...res.goods]
        })

        //关闭下拉刷新的窗口
        wx.stopPullDownRefresh()
    },
    /// 接受从子组件传递过来的标题点击事件
    handleTabsChange(e) {
        /// 获取事件索引
        const { index } = e.detail;
        let { tabs } = this.data;
        tabs.forEach((v, i) => {
            i === index ? v.isActive = true : v.isActive = false
        })
        this.setData({
            tabs
        })
    },
    onReachBottom() {
        if (this.innerParams.pagenum >= this.totalPages) {
            wx.showToast({
                title: '没有下一页数据'
            });
        } else {
            this.innerParams.pagenum++;
            this.getGoodsList()
        }
    },
    onPullDownRefresh() {
        //重置数组
        this.setData({
            goodsList: []
        })
        //重置页码
        this.innerParams.pagenum = 1;
        this.getGoodsList()
    },
    mySort: function (e) {
        //property 根据什么排序
        var property = e.currentTarget.dataset.property;
        var self = this;
        var arr = self.data.arr;
        var sortRule = true; // 正序倒序
        self.setData({
            arr: arr.sort(self.compare(property, sortRule))
        })
        //console.log(arr)
    },
    compare: function (property, bol) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (bol) {
                return value1 - value2;
            } else {
                return value2 - value1;
            }
        }
    }
})
